<?php
namespace app\serverfund\logic;

use \app\manage\logic\BaseLogic;
use \think\Db;
/**
 * @author:      李颖
 * @DateTime:    2017-08-31 11:14:12
 * @Description: 提现模块
 */
class Withdraw extends BaseLogic
{
    protected $name = 'withdraw';
    protected $config = 'db_config_fund';
    private $withdrawModel = '\app\serverfund\model\Withdraw';
    protected $allowField = ['user_id','app_id','user_info','type','card_id','card_info','money','create_time','update_time','review_info','transfer_info'];

    /*我的 - 申请提现*/
    public function applyDrawwith($data): array 
    {
        $this->db()->startTrans();
        try{
            //申请提现记录表中添加记录 + 冻结该用户资金
            $data['review_info'] = [];
            $data['transfer_info'] = [];
            $addWithdraw = $this->model($this->withdrawModel)->allowField($this->allowField)->save($data);
            $freezeData['obj_id'] = $this->model($this->withdrawModel)->getLastInsID();
            $freezeData['user_id'] = $data['user_id'];
            $freezeData['opposite_id'] = SYSTEM_ID;
            $freezeData['money'] = $data['money'];
            $freezeData['update_ip'] = $data['update_ip'];
            $freezeData['app_id'] = $data['app_id'];
            $freezeData['user_info'] = json_encode($data['user_info']);
            $freezeData['opposite_info'] = isset($data['opposite_info']) ? $data['opposite_info'] : json_encode(['name'=>'system']);
            $freezeData['type'] = 'withdraw';
            $freezeData['freeze_counts'] = 1;
            $freezeRes = logic('\app\serverfund\logic\FundAccount')->freeze($freezeData);
            if($freezeRes['status'] != SUCCESS_STATUS){
                return $freezeRes;
            }
            // 提交事务
            $this->db()->commit();
        } catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($freezeRes);

    }

    /*我的 - 申请提现列表（分页）*/
    public function withdrawList($data): array 
    {
        if(isset($data['keywords']) && $data['keywords']){ $_where['user_info$.name|user_info$.id|card_info$.name|card_info$.number'] = ['like', '%' . $data['keywords'] . '%']; }
    	if(isset($data['user_id']) && $data['user_id']){ $_where['user_id'] = $data['user_id']; }
    	if(isset($data['status']) && $data['status'] !== ''){
            $_where['status'] = $data['status']; 
        }else{
            $_where['status'] = ['in',[0,1,2,3,4]];
        }
        if(isset($data['time'])){
            $threeMonthTime = mktime(0, 0, 0, date("m")-3, date("d"), date("Y"));
            if($data['time'] == 'threeMonthAgo'){   
                $_where['create_time'] = ['lt',$threeMonthTime];    //3个月以前
            }elseif($data['time'] == 'threeMonth'){   
                $_where['create_time'] = ['gt',$threeMonthTime];    //3个月之内
            }
        }
    	$res = $this->model($this->withdrawModel)
                    ->where($_where)
                    ->order('id DESC')
                    ->paginate($data['listRows'], false, ['page'=>$data['page']])
                    ->toArray();
        return auto_return_page($res, '已找到提现列表数据', '没有提现列表数据');
    }

    /*管理员 - 审核提现*/
    /*审核成功：修改为审核成功状态
    审核失败：修改为审核失败状态 + 解冻用户资金*/
    public function auditWithdraw($data): array 
    {
        $this->db()->startTrans();
        try{
            //修改提现记录状态
            $_where['id'] = $data['id'];
            $_where['status'] = 0;
            $withdrawInfo = $this->model($this->withdrawModel)->where($_where)->find();
            if(!$withdrawInfo){
                return verify_err(null, '未找到相应的提现记录');
            }

            $saveData['status'] = $data['status'];
            $saveData['review_id'] = $data['review_id'];
            $saveData['review_info'] = $data['review_info'];
            $updateRes = $this->model($this->withdrawModel)->save($saveData, $_where);

            if($data['status'] == 2){  //审核失败：解冻用户资金
                $unfreezeData['user_id'] = $withdrawInfo['user_id'];
                $unfreezeData['opposite_id'] = $data['review_id'];
                $unfreezeData['type'] = 'withdraw';
                $unfreezeData['obj_id'] = $data['id'];
                $unfreezeData['freeze_counts'] = 1;
                $unfreezeData['money'] = $withdrawInfo['money'];
                $unfreezeData['update_ip'] = $data['update_ip'];
                $unfreezeData['app_id'] = $withdrawInfo['app_id'];
                $unfreezeData['user_info'] = json_encode($withdrawInfo['user_info']);
                $unfreezeData['opposite_info'] = json_encode($data['review_info']);
                $unfreezeRes = logic('\app\serverfund\logic\FundAccount')->unfreeze($unfreezeData);
                if($unfreezeRes['status'] != SUCCESS_STATUS){
                    return $unfreezeRes;
                }
            }
            /*if($data['status'] == 1){ //审核通过
                //用户转账给平台
                $transferData['user_id'] = $withdrawInfo['user_id'];
                $transferData['opposite_id'] = SYSTEM_ID;
                $transferData['money'] = $withdrawInfo['money'];
                $transferData['update_ip'] = $data['update_ip'];
                $transferData['app_id'] = $data['app_id'];
                $transferData['user_info'] = json_encode($withdrawInfo['user_info']);
                $transferData['opposite_info'] = json_encode(['name'=>'system']);
                $transferRes = logic('\app\serverfund\logic\FundAccount')->transfer($transferData);
                if($transferRes['status'] != SUCCESS_STATUS){
                    return $transferRes;
                }
            }*/
            // 提交事务
            $this->db()->commit();
        }catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($updateRes);
    }

    /*管理员 - 审核转账
      转让成功： 修改为转让成功状态 + 解冻用户资金 + 用户资金转让给平台
      转让失败： 修改为转让失败状态 + 解冻用户资金
    */
    public function auditTransfer($data): array 
    {
        $_where['id'] = $data['id'];
        $_where['status'] = 1;
        $saveData['status'] = $data['status'];
        $saveData['transfer_id'] = $data['transfer_id'];
        $saveData['transfer_info'] = $data['transfer_info'];
        //开启事务
        $this->db()->startTrans();
        try{
            $withdrawInfo = $this->model($this->withdrawModel)->where($_where)->find();
            if(!$withdrawInfo){
                return verify_err(null, '未找到相应的提现记录');
            }
            //修改状态
            $res = $this->model($this->withdrawModel)->save($saveData, $_where);
            //解冻用户资金
            $unfreezeData['user_id'] = $withdrawInfo['user_id'];
            $unfreezeData['opposite_id'] = $data['transfer_id'];
            $unfreezeData['type'] = 'withdraw';
            $unfreezeData['obj_id'] = $data['id'];
            $unfreezeData['freeze_counts'] = 1;
            $unfreezeData['money'] = $withdrawInfo['money'];
            $unfreezeData['update_ip'] = $data['update_ip'];
            $unfreezeData['app_id'] = $withdrawInfo['app_id'];
            $unfreezeData['user_info'] = json_encode($withdrawInfo['user_info']);
            $unfreezeData['opposite_info'] = json_encode($data['transfer_info']);
            $unfreezeRes = logic('\app\serverfund\logic\FundAccount')->unfreeze($unfreezeData);
            if($unfreezeRes['status'] != SUCCESS_STATUS){
                return $unfreezeRes;
            }
            if($data['status'] == 4){ //后台转账成功给用户后： 用户资金支付给平台
                $transferData['user_id'] = $withdrawInfo['user_id'];
                $transferData['opposite_id'] = SYSTEM_ID;
                $transferData['money'] = $withdrawInfo['money'];
                $transferData['update_ip'] = $data['update_ip'];
                $transferData['app_id'] = $data['app_id'];
                $transferData['user_info'] = json_encode($withdrawInfo['user_info']);
                $transferData['opposite_info'] = json_encode(['name'=>'system']);
                $transferRes = logic('\app\serverfund\logic\FundAccount')->transfer($transferData);
                if($transferRes['status'] != SUCCESS_STATUS){
                    return $transferRes;
                }
            }
            // 提交事务
            $this->db()->commit();
        }catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($res);
    }

}